package com.kika.obwiki.controller;

import com.kika.obwiki.resp.CommonResp;
import com.kika.obwiki.service.IDocService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import javax.validation.Valid;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import com.kika.obwiki.resp.DocQueryResp;
import com.kika.obwiki.rep.DocQueryReq;
import com.kika.obwiki.rep.DocSaveReq;
import com.kika.obwiki.resp.PageResp;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Arrays;
import java.util.stream.Collectors;
import com.kika.obwiki.exception.BusinessException;
import com.kika.obwiki.exception.BusinessExceptionCode;
import com.kika.obwiki.utils.RequestContext;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cr
 * @since 2025-06-22
 */
@RestController
@RequestMapping("/doc")
public class DocController {

    @Autowired
    private IDocService docService;

    /**
     * 根据电子书ID查询所有文档
     * 
     * @param ebookId 电子书ID
     * @return 通用响应，包含文档列表
     */
    @GetMapping("/all/{ebookId}")
    public CommonResp all(@PathVariable String ebookId) {
        System.out.println(
                "收到查询请求 ebookId=" + ebookId + " 类型=" + (ebookId == null ? "null" : ebookId.getClass().getName()));
        Long id = null;
        try {
            id = Long.valueOf(ebookId);
        } catch (Exception e) {
            System.out.println("ebookId转Long失败: " + e.getMessage());
            return new CommonResp(false, "ebookId参数错误", null);
        }
        List<DocQueryResp> list = docService.all(id);
        System.out.println("返回文档数=" + (list == null ? 0 : list.size()));
        if (list != null && !list.isEmpty()) {
            for (DocQueryResp doc : list) {
                System.out.println("文档: id=" + doc.getId() + ", ebookId=" + doc.getEbookId() + ", parent="
                        + doc.getParent() + ", name=" + doc.getName());
            }
        }
        CommonResp<List<DocQueryResp>> resp = new CommonResp<>(true, "查询成功", list);
        return resp;
    }

    /**
     * 查询所有文档
     * 
     * @return 通用响应，包含文档列表
     */
    @GetMapping("/all")
    public CommonResp all() {
        CommonResp<List<DocQueryResp>> resp = new CommonResp<>(true, "查询成功", null);

        List<DocQueryResp> list = docService.all();
        resp.setContent(list);
        return resp;
    }

    /**
     * 分页查询文档
     * 
     * @param req 查询请求参数
     * @return 通用响应，包含分页结果
     */
    @GetMapping("/list")
    public CommonResp list(@Valid DocQueryReq req) {
        CommonResp<PageResp<DocQueryResp>> resp = new CommonResp<>(true, "查询成功", null);

        PageResp<DocQueryResp> pageResp = docService.listByname(req);
        resp.setContent(pageResp);

        return resp;
    }

    /**
     * 保存文档（新增或更新）
     * 
     * @param req 保存请求参数
     * @return 通用响应
     */
    @PostMapping("/save")
    public CommonResp save(@Valid @RequestBody DocSaveReq req) {
        CommonResp resp = new CommonResp<>(true, "成功", null);
        docService.save(req);
        return resp;
    }

    /**
     * 删除文档
     * 
     * @param id 文档ID
     * @return 通用响应
     */
    @DeleteMapping("/delete/{id}")
    public CommonResp delete(@PathVariable Long id) {
        CommonResp resp = new CommonResp<>(true, "删除成功", null);
        docService.delete(id);
        return resp;
    }

    /**
     * 批量删除文档
     * 
     * @param ids 文档 id 列表，以逗号分隔的字符串
     * @return 通用响应
     */
    @GetMapping("/remove")
    public CommonResp delete(@RequestParam("ids") String ids) {
        System.out.println("收到删除请求，ids=" + ids);
        CommonResp resp = new CommonResp(true, "删除成功", null);

        // 将逗号分隔的字符串转换为Long列表
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim)
                .map(Long::valueOf)
                .collect(Collectors.toList());

        docService.delete(idList);
        return resp;
    }

    /**
     * 文档点赞接口
     * 
     * @param id 文档ID
     * @return 通用响应
     */
    @GetMapping("/vote/{id}")
    public CommonResp vote(@PathVariable Long id, javax.servlet.http.HttpServletRequest request) {
        // 登录校验：判断header中token是否存在
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            throw new BusinessException(BusinessExceptionCode.VOTE_NEED_LOGIN);
        }
        CommonResp commonResp = new CommonResp();
        docService.vote(id);
        return commonResp;
    }
}
